import React, { Component } from 'react'
import { Timeline, message } from 'antd';
import u from '../../../common.js'
import '../../../static/routineMonitoring/wechat.less'

class Wechat extends Component{
  constructor(props) {
    super(props)
    this.state = {
      qunList: [],
      qunListDetail: [],
      keyWordList: [],
      type: '0',
      detailType: '1',
      startTime: '',
      endTime: '',
      colorFlag: false,
      colorFlag2: false,
      zhazhaoIf: true,
      keyWordName: '',
      keyWordName2: '',
      searchGroupList: [],
      searchMemberList: [],
      GroupTotal: null,
      total: null,
      id: '',
      yujingFlag: '',
      indexId: null,
      addList: [],
      selectChangeColor: null,
      wordFlag: false,
      wordFlag2: false,
      totalMember: 0,
      showAlllist: [],
      showAllIf: false,
      titleName: '',
      choseDate: 10,
      msgId: null,
      clickIf: false,
      flag: null,
      bubianNum: 0,
      scrollTopLength: null,
      imageStatus: null
    }
  }

  componentDidMount() {
    u.selectWord(data =>{
      if(!data) return
      this.setState({
        keyWordList: data.data
      })
    })
    this.getWeiXinQun()
    this.getWeiXinQunDetail()
    this.getMember()
  }

  onCancelAdd(id) {
    let userId = localStorage.getItem('userId')
    u.cancelAdd({
      userId: userId,
      id: id
    },data=>{
      this.getMember()
      this.getWeiXinQun()
      message.success('取消成功');
    })
  }

  getWeiXinQun() {
    let {type,startTime,endTime,keyWordName} = this.state
    let userId = localStorage.getItem('userId')
    u.weiXinQun({
      name: keyWordName,
      type: type,
      startTime: startTime,
      endTime: endTime,
      userId: userId
    },data =>{
      let type = this.state.type
      if (!data) return
      if (type === '0') {
        let list = data.groupList
        this.setState({
          qunList: list
        })
      }
      if (type === '1') {
        let searchGroupList = data.groupList
        let searchMemberList = data.memberList
        let total = data.memberListTotal
        this.setState({
          searchGroupList: searchGroupList,
          searchMemberList: searchMemberList.slice(0,5),
          totalMember:total,
          showAlllist: searchMemberList
        })
        if(searchGroupList.length === 0 && searchMemberList.length === 0) {
          message.success('未搜索到相关用户或群组')
        } else if (searchMemberList.length === 0) {
          message.success('未搜索到相关用户')
        } else if(searchGroupList.length === 0) {
          message.success('未搜索到相关群组')
        }
      }
    })
  }

  onShowAll() {
    this.setState({
      showAllIf: !this.state.showAllIf
    },() =>{
      let showAllIf = this.state.showAllIf
      if(showAllIf){
        let showAlllist = this.state.showAlllist
          this.setState({
            searchMemberList: showAlllist
          })
      }
    })
  }

  onSearchWeixinQun(word) {
    let name = this.state.keyWordName
    if(!name.trim()) {
      word = '0'
    }
    this.setState({
      type: word,
      keyWordName: word === '0' ? '' : name,
      showAllIf: false
    },() =>{
      this.getWeiXinQun()
    })
  }


  onQunListDetail(groupId,flag,num,type,titleName) {
    if(titleName === undefined) {
      titleName = ''
    }
    this.setState({
      id: groupId,
      yujingFlag: num,
      detailType: type,
      titleName: titleName,
      flag: flag
    },() =>{
      this.getWeiXinQunDetail()
    })
  }

  // 重点人/组织检测总览
  onWeiXinQunYuJing() {
    this.setState({
      startTime: '',
      endTime: '',
      keyWordName2: '',
      id: '',
      detailType: '1',
      yujingFlag: '',
      clickIf: false,
      selectChangeColor: null,
      msgId: null,
      flag: null
    },() =>{
      this.getWeiXinQunDetail()
      this.getWeiXinQun()
    })
  }

  onSearchKeyWord() {
    let id = this.state.id
    this.setState({
      flag: this.state.flag,
      yujingFlag: '',
      id: id,
      detailType: this.state.keyWordName2?'0':'1',
      // selectChangeColor: null,
      keyWordName2: this.state.keyWordName2
    },() =>{
      this.getWeiXinQunDetail()
    })
  }
  onResetKeyWord() {
    let id = this.state.id
    this.setState({
      flag: this.state.flag,
      yujingFlag: '',
      id: id,
      detailType: this.state.keyWordName2?'0':'1',
      keyWordName2: '',
    },() =>{
      this.getWeiXinQunDetail()
    })
  }

  onWhereQun(groupId,flag,num,type,msgId,click) {
    this.setState({
      msgId:msgId,
      clickIf: click,
      flag: flag
    })
    let [list,srcoll] = [this.state.qunList,null]

    list.some((el,index) => {
      this.setState({
        selectChangeColor: index,
        titleName: el.group_name
      })
      if(el.group_openId === groupId){
        srcoll = u.queryAll('.listDetail')[index].offsetTop - 56;
        scrollTop()
        return true
      }
    }) 

    function scrollTop () {
      if(u.query('.leftContent').scrollTop){
        let num = u.query('.leftContent').scrollTop
        console.log(num)
        if(Math.abs(num-srcoll) < 5) {
          u.query('.leftContent').scrollTop =srcoll
          return
        }
        if(num< srcoll) {
          u.query('.leftContent').scrollTop+= 5
          requestAnimationFrame(scrollTop)
        }else if(num > srcoll){
          u.query('.leftContent').scrollTop-= 5
          requestAnimationFrame(scrollTop)
        }
      }
      
    }
    this.onQunListDetail(groupId,flag,num,type)
  }

  getWeiXinQunDetail() {
    let { detailType, startTime, endTime, keyWordName2, id, flag} = this.state
     u.weixinQunDetail({
      type: detailType,
      startTime: startTime,
      endTime: endTime,
      keyWord: keyWordName2,
      id: id,
      flag: flag
    },data =>{
      this.setState({
        total: data.total,
        GroupTotal: data.GroupTotal,
        qunListDetail: data.result,
      },() =>{
        let srcoll = null
        let msgId = this.state.msgId
        let clickIf = this.state.clickIf  
      
      if (this.state.selectChangeColor === null ){
        this.setState({
          bubianNum: data.total
        })
      }
      if (clickIf === true) {
        data.result.some((el,index) =>{
          if(el.msg_id === msgId) {
            srcoll = u.queryAll('.ant-timeline-item.listDetailStyle')[index].offsetTop - 260
            scrollTop()
          }
  
          function scrollTop () {
            if(u.query('.yujingDetail').scrollTop){
              let num = u.query('.yujingDetail').scrollTop
              if(Math.abs(num-srcoll) < 5) {
                u.query('.yujingDetail').scrollTop =srcoll
                return
              }
              if(num< srcoll) {
                u.query('.yujingDetail').scrollTop+= 5
                requestAnimationFrame(scrollTop)
              }else if(num > srcoll){
                u.query('.yujingDetail').scrollTop-= 5
                requestAnimationFrame(scrollTop)
              }
            }
          }
        })
      }
      })
    })
  }

  onChoseTime(num) {
    let endTime = u.getDate(0,true)
    let startTime = u.getDate(num,false)
    this.setState({
      startTime: num === 10 ? '' : startTime,
      endTime: num === 10 ? '' : endTime,
      choseDate: num
    },() => {
      // this.getWeiXinQun()
      this.getWeiXinQunDetail()
    })
  }

  onMouseMove() { 
    this.setState({
      colorFlag: !this.state.colorFlag
    })
  }

  onMouseMove2() { 
    this.setState({
      colorFlag2: !this.state.colorFlag2
    })
  }

  onDingWei(e){
    // console.log(e.target.scrollTop)
  }

  onDingWei2(e){
    this.setState({
      scrollTopLength: e.target.scrollTop
    })
  }

  onShow(){
    this.setState({
      zhazhaoIf: !this.state.zhazhaoIf
    },() =>{
      let panduan = this.state.zhazhaoIf
      if (panduan === true) {
        this.getMember()
      }
    })
  }

  // 增加用户列表
  getMember() {
    let userId = localStorage.getItem('userId')
    u.yiguanzhu({
      userId: userId
    }, data=>{
      this.setState({
        addList: data
      })
    })
  }
  
  onSearchWord(e) {
    this.setState({
      keyWordName: e.target.value
    },() =>{
      let wordLength = this.state.keyWordName.trim()
      if (wordLength.length > 0) {
        this.setState({
          wordFlag: true
        })
      } else{
        this.setState({
          wordFlag: false
        })
      }
    })
  }
  onSearchWord2(e) {
    this.setState({
      keyWordName2: e.target.value
    },() =>{
      let wordLength = this.state.keyWordName2.trim()
      if (wordLength.length > 0) {
        this.setState({
          wordFlag2: true
        })
      } else{
        this.setState({
          wordFlag2: false
        })
      }
    })
  }

  onAdd(groupId) {
    let userId = localStorage.getItem('userId')
    u.attention({
      userId: userId,
      type: '0',
      id: groupId,
    },data=>{
      this.getWeiXinQun()
      this.getMember()
      message.success('关注成功');
    })
  }
  onSelectChangeColor(index) {
    this.setState({
      selectChangeColor: index
    })
  }

  //点击回到顶部
  goTop() {
    let bigBox = document.querySelector('.yujingDetail');
    bigBox.scrollTop = 0
  }

  // 图片加载失败
  handleImageErrored(e) {
    e.target.src=require('../../../static/image/morentouxiang.png')
  }

  handleImageErrored2(e) {
    e.target.src=require('../../../static/image/quntouxiang.png')
  }

  render() {
    return (
      <div className="wechat">
        <div className='wechatBox leftstyle'>
          <div className="searchBox3">
            <input className={this.state.colorFlag?'inputStyle3 hover': 'inputStyle3'}
              value={this.state.keyWordName}
              onFocus={this.onMouseMove.bind(this)}
              onBlur={this.onMouseMove.bind(this)} type="text" placeholder="搜索微信群、重点人…"
              onChange={this.onSearchWord.bind(this)}
            />
              <img onClick={this.onSearchWeixinQun.bind(this,'1')} className="searchStyle3" src={require("../../../static/image/search.png") }/>
            {
              this.state.wordFlag?
              <img onClick={this.onSearchWeixinQun.bind(this,'0')} className="cancelStyle3" src={require("../../../static/image/cancel.png") }/>
              :''
            }
          </div>
          <div onScroll={(e) => {this.onDingWei(e)}} className='leftContent'>
          { 
            this.state.type === '0'?
            <div onClick={this.onWeiXinQunYuJing.bind(this)} className={this.state.selectChangeColor === null?'yujingtishi':'noSelect'}>
              <div className='tishi_left'>
                <img src={require('../../../static/image/jinggao_03.png')} />
              </div>
              <div className='tishi_right'>
                <div className='right_top'>微信群预警({this.state.bubianNum?this.state.bubianNum: 0})</div>
                <div className='zhongdianren'>重点人/组织检测总览</div>
              </div>
            </div>: ''
          }

            {
              this.state.type === '0'?
              this.state.qunList.map((item,index) =>{
                return(
                  <div key={index} onClick={this.onSelectChangeColor.bind(this,index)} className={this.state.selectChangeColor === index?'listDetail selectStyle':'listDetail'}>
                    <div className='listPic'>
                      {/* <img src={u.imgUrl + item.group_head_img_url} /> */}
                      <img src={u.imgUrl + item.group_head_img_url} 
                        // onLoad={this.handleImageLoaded.bind(this,item.group_head_img_url)}
                        onError={this.handleImageErrored.bind(this)}
                      />
                    </div>
                    {/* 左边列表 */}
                    <div onClick={this.onQunListDetail.bind(this,item.group_openId,'0','0','2',item.group_name)} className='listContent4'>
                      <div className='listTop'>{ item.group_name }</div>
                      <div className='listButton'>
                      {
                        this.state.selectChangeColor === index?<img src={require('../../../static/image/rentou2.png')} />:<img src={require('../../../static/image/rentou.png')} />
                      }
                        <span>{ item.memberTotal }</span>
                      </div>
                    </div>
                    <div className="listAdd">
                      <div className='listAddLogo'>
                        {
                          item.isCollect === 1?'':<img onClick={this.onAdd.bind(this,item.group_openId)} src={require('../../../static/image/add_06.png')} />
                        }
                      </div>
                      <div className='listAddcontent'>{item.isCollect ===1?'已关注':''}</div>
                    </div>
                  </div>
                )
              }):''
            }

            {/* 显示搜索结果 */}
            { this.state.type === '1'?
              <div className='searchEndStyle'>
              {
                this.state.searchMemberList.length !== 0 ?  <div className='searchTitle'>微信用户</div> :''
              }
                <div className='searchList'>
                {
                  this.state.searchMemberList.map((item,index) =>{
                    return(
                      // 左边搜索群
                      <div onClick={this.onQunListDetail.bind(this,item.wxId,'1','1','2',item.group_name)} className='searchTop' key={index}>
                        <div className='searchImg'>
                          <img src={u.imgUrl + item.head_img_url} 
                            // onLoad={this.handleImageLoaded.bind(this,item.head_img_url)}
                            onError={this.handleImageErrored.bind(this)}
                          />
                        </div>
                        <div className='searchContent'>
                          <div className='content1' dangerouslySetInnerHTML={{__html: item.nickName.replace(this.state.keyWordName,'<span style="color:#5287ff;">'+this.state.keyWordName+'</span>')}}></div>
                          {/* <div className='content1'>{ item.nickName }</div> */}
                          <div className='content2'>微信号：{ item.wxId }</div>
                        </div>
                      </div>
                    )
                  })
                }
                {
                  this.state.totalMember > 5? (!this.state.showAllIf?
                    <div onClick={ this.onShowAll.bind(this) } className='showAll'>显示全部({ this.state.totalMember })</div>
                    :''): ''
                }
                {/* {
                  !this.state.showAllIf?
                  <div onClick={ this.onShowAll.bind(this) } className='showAll'>显示全部({ this.state.totalMember })</div>
                  :''
                } */}
                  </div>
                {
                  this.state.searchGroupList.length !== 0 ? <div className='searchTitle'>群组</div>: ''
                }
                
                <div className='searchList2'>
                {
                  this.state.searchGroupList.map((item,index) =>{
                    return (
                       // 左边搜索人
                      <div onClick={this.onQunListDetail.bind(this,item.group_openId,'0','0','2',item.group_name)} key={index} className='searchBottom'>
                        <div className='searchImg'>
                          <img src={u.imgUrl + item.group_head_img_url} 
                          onError={this.handleImageErrored2.bind(this)} />
                        </div>
                        <div className='searchContent'>
                          <div className='content1' dangerouslySetInnerHTML={{__html: item.group_name.replace(this.state.keyWordName,'<span style="color:#5287ff;">'+this.state.keyWordName+'</span>')}}></div>
                          {/* <div className='content1'>{ item.group_name.replace('福利','<span style="color:#32b144;">$1</span>') }</div> */}
                          <div className='content2'>
                            <img src={require('../../../static/image/rentou.png')} />
                            { item.memberTotal }
                          </div>
                        </div>
                        <div className="listAdd">
                          <div className='listAddLogo'>
                            {
                              item.isCollect === 1?'':<img onClick={this.onAdd.bind(this,item.group_openId)} src={require('../../../static/image/add_06.png')} />
                            }
                          </div>
                          <div className='listAddcontent'>{item.isCollect ===1?'已关注':''}</div>
                        </div>
                      </div>
                    )
                  })
                }
                </div>
              </div>: ''
            }
           
          </div>
        </div>
        <div className='wechatBox middle'>
          <div className='title'>
            <div className="title_left">{this.state.titleName && this.state.selectChangeColor!== null?this.state.titleName:'微信群预警'}<span>{this.state.total?this.state.total: 0}</span>
            {
              this.state.GroupTotal === undefined?'': <span>/{this.state.GroupTotal?this.state.GroupTotal:0}</span>
            }
          </div>
            <div className="title_right3">
              <div className="right_postion3">
                <input className={this.state.colorFlag2?'inputStyle4 hover': 'inputStyle4'}
                  value={this.state.keyWordName2}
                  onFocus={this.onMouseMove2.bind(this,true)}
                  onBlur={this.onMouseMove2.bind(this,false)}
                  onChange={this.onSearchWord2.bind(this)}
                  type="text" placeholder="搜索关键词…"/>
                  <img onClick={this.onSearchKeyWord.bind(this)} className="searchStyle4" src={require("../../../static/image/search.png") }/>
                  {
                    this.state.wordFlag2?
                    <img onClick={this.onResetKeyWord.bind(this)} className="cancelStyle4" src={require("../../../static/image/cancel.png") }/>
                    : ''
                  }
              </div>
            </div>
          </div>
          <div className='zhezhao'>
            {
              this.state.zhazhaoIf?
              <div  className='zhezhaoBox'>
                {
                  this.state.addList.map((item,index) =>{
                    return(
                      // 右边搜索列表
                      <div onClick={this.onWhereQun.bind(this,item.group_openId,'0','0','2',null,false)} key={index} className='zhezhaoList'>
                        <img className='zhezhaotouxiang' src={u.imgUrl + item.group_head_img_url}
                        onError={this.handleImageErrored.bind(this)} />
                        <div className='zhezhaoContent'>
                          <div className='zhezhaoTop'>
                            <div>{ item.group_name }</div>
                            <div onClick={this.onCancelAdd.bind(this,item.group_openId)} className='pointer'><img className='zhezhaotouxiang' src={require('../../../static/image/jianhao.png')} /></div>
                          </div>
                          <div>微信号：{ item.wxId }</div>
                        </div>
                      </div>
                    )
                  })
                }
            </div>: ''
            }
            {
              (this.state.zhazhaoIf && this.state.addList.length !== 0)?<div className='sanjiao'><img src={require('../../../static/image/sanjiao_03.png')} /></div>:''
            }
            {/* {
              !this.state.zhazhaoIf?<div className='circle'>+1</div>:''
            } */}
            <img onClick={this.onShow.bind(this)} className='imgStyle' src={require('../../../static/image/zhezhaorentou.png')} />
            {
              this.state.scrollTopLength >= 300 ? <img className='imgStyle1' onClick={this.goTop.bind(this)} src={require('../../../static/image/retract.png')}/>: ''
            }
            
          </div>
          <div onScroll={(e) => {this.onDingWei2(e)}}  className='yujingDetail'>
          {
            this.state.qunListDetail.length !== 0 ?
            <Timeline>
              { 
                this.state.qunListDetail.map((item,index) =>{
                  return (
                    <Timeline.Item className='listDetailStyle' key={index}>
                      <span className='detailTimeStyle'>
                        { u.unixTime(Number(item.addTime)) }
                      </span>
                      <div className='itemList'>
                        <div className='touxiang'>
                          <img src={u.imgUrl + item.url}
                            onError={this.handleImageErrored.bind(this)} 
                          />
                        </div>
                        <div className='detailList'>
                          <div className='detailTitle'>
                            <span>{ item.present_user_name }</span>
                            {this.state.selectChangeColor === null?
                            // 右边点击跳转
                            <div className='showClickStyle'>-来自群组<span onClick={this.onWhereQun.bind(this,item.group_id,'0','0','2',item.msg_id,true)} className='qunzhuColor'>{ item.group_nickname }</span><a href=''></a></div>:''}
                          </div>
                          <div className='detailContent' dangerouslySetInnerHTML={{__html: item.content}}>
                          </div>
                        </div>
                      </div>
                    </Timeline.Item>
                  )
                })
              }
            </Timeline>:
            <div className='nothing'>
              <div className='nothing_pos'>
                <div>
                  <img src={require('../../../static/image/nothing.png')}/>
                </div>
                <div className='zhanwuneirong'>暂无内容</div>
              </div>
            </div>
          }
            
          </div>
        </div>
        <div className='wechatBox right'>
          <div className='title'>筛选信息</div>
          <div className='yujingBox1'>
            <div className='yujingKeyWrod'>预警关键词</div>
            <div className='keyWord'>
            {
              this.state.keyWordList.map((item,index) =>{
                return(
                  <div key={index}>
                    {item.name}
                  </div>
                )
              })
            }
            </div>
          </div>
          <div className="timeStyle">时间</div>
          <div className="timeKeyWord">
            <div onClick={this.onChoseTime.bind(this,10)}
              className={this.state.choseDate === 10?'allKeyWord':'keyWordTime'}>全部</div>
            <div onClick={this.onChoseTime.bind(this,0)} 
              className={this.state.choseDate === 0?'allKeyWord':'keyWordTime'}>近一日</div>
            <div onClick={this.onChoseTime.bind(this,3)}
              className={this.state.choseDate === 3?'allKeyWord':'keyWordTime'}>近三日</div>
            <div onClick={this.onChoseTime.bind(this,7)}
              className={this.state.choseDate === 7?'allKeyWord':'keyWordTime'}>近一周</div>
          </div>
        </div>
      </div>
    )
  }
}

export default Wechat